package MySql;

import Bean.Blog;

import java.sql.*;
import java.util.Vector;

/**
 * Created by liushiyin on 17-11-17.
 */
public class MySqlTool {
    private static final String REMOTE_IP = "localhost";
    private static final String URL = "jdbc:mysql://" + REMOTE_IP + "/myweb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
    private static final String USER = "root";
    private static final String PASSWORD = "3252918599lsy,;";
    private static final String driverName="com.mysql.jdbc.Driver";
    private Connection con=null;

    public MySqlTool(){
        try{
            // 注册 JDBC 驱动
            Class.forName(driverName);
            // 打开链接
            System.out.println("连接数据库...");
            con = DriverManager.getConnection(URL,USER,PASSWORD);
            System.out.println("连接数据库成功!");
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
            System.out.println("连接数据库失败!");
        }
    }

    public boolean QueryExits(String query){
        PreparedStatement ps=null;
        ResultSet resultSet=null;
        try {
            ps=con.prepareStatement(query);
            resultSet=ps.executeQuery();
            resultSet.next();
            resultSet.getString(1);
            resultSet.close();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean insert(String sql){
        try {
            PreparedStatement ps=con.prepareStatement(sql);
            return ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public Vector<Blog> queryBlogs(String sql){
        Vector<Blog> lists=new Vector<>();
        try {
            PreparedStatement ps=con.prepareCall(sql);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                Blog blog=new Blog();
                blog.setBlogTitle(rs.getString(1));
                blog.setBlogText(rs.getString(2));
                lists.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return lists;
    }

    public void close(){
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
